package com.birdboot.controller;

import com.birdboot.entity.User;
import com.birdboot.http.HttpServletRequest;
import com.birdboot.http.HttpServletResponse;

import java.io.*;
/**
 *  V13新增内容
 *  处理用户相关业务的类
 */
public class UserController {

    //用于表示存储所有用户文件的users目录
    private static File userDir;
    static{
            /* File baseDir = new File(UserController.class.
                    getClassLoader().getResource(".").toURI());
            userDir = new File(baseDir,"/localFile/user");*/
        userDir = new File("./localFile/user");
        if(!userDir.exists()){
            userDir.mkdirs();
        }
    }
    /**
     * 处理用户注册
     * @param request
     * @param response
     */
    public void reg(HttpServletRequest request, HttpServletResponse response){
        //1通过request获取表单数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String nickname = request.getParameter("nickname");
        String ageStr =request.getParameter("age");
        System.out.println(username+", "+password+", "+nickname+", "+ageStr);
        //必要的验证
        if(username==null || username.isEmpty() ||
           password==null || password.isEmpty() ||
           nickname==null || nickname.isEmpty() ||
           ageStr==null || ageStr.isEmpty() ||
           !ageStr.matches("\\d+")){
            //跳转注册失败页面
            response.sendRedirect("/reg_info_error.html");
            return;
        }

        int age = Integer.parseInt(ageStr);
        User user = new User(username,password,nickname,age);

        File file = new File(userDir,username+".obj");
        if(file.exists()){
            response.sendRedirect("/have_user.html");
            return;
        }

        try(FileOutputStream fos = new FileOutputStream(file);
            ObjectOutputStream oos = new ObjectOutputStream(fos);
        ){
            oos.writeObject(user);
            response.sendRedirect("/reg_success.html");
            return;
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
